package com.gzhryc.shared_device.oem.code.agent.services;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.agent.dao.AgentReferrerBusinessConfigDao;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentReferrerBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.models.AgentReferrerCount;
import com.gzhryc.shared_device.oem.code.agent.dao.models.AgentReferrerUser;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentReferrerBusinessConfigSearch;
import com.gzhryc.shared_device.oem.code.config.BusinessConfig;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;

public class AgentReferrerBusinessConfigService {

	static Logger log = Logger.getLogger(AgentReferrerBusinessConfigService.class);

    public static AgentReferrerBusinessConfigService self() {
        return MultiDBTools.getService(AgentReferrerBusinessConfigService.class, true);
    }

    public static AgentReferrerBusinessConfigService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, AgentReferrerBusinessConfigService.class, true);
    }

    AgentReferrerBusinessConfigDao dao;

    public AgentReferrerBusinessConfigService(String jdbcKey) {
        this.dao = new AgentReferrerBusinessConfigDao(jdbcKey);
    }
    
    public List<AgentReferrerBusinessConfig>findJoinBySearch(AgentReferrerBusinessConfigSearch search
    		,Integer pageNo,Integer pageLimit){
    	Conditions condition = dao.buildConditions(search);
    	condition.and().likeBoth("user.name", search.getUserName());
    	condition.and().is("user.phone", search.getUserPhone());
    	
    	try {
    		List<AgentReferrerBusinessConfig> data =  dao.findJoinByCondition(condition, pageNo, pageLimit);
			if(data != null && data.size() > 0) {
				List<Long> userIds = new ArrayList<Long>();
				for(AgentReferrerBusinessConfig item : data) {
					userIds.add(item.getUserId());
				}
			
				List<AgentBusinessConfig> agentBusiCfgList = AgentBusinessConfigService.self().findByUserId(userIds);
				if(agentBusiCfgList != null && agentBusiCfgList.size() > 0) {
					BusinessConfig busiCfg = ConfigUtils.getBusinessConfig();
					for(AgentReferrerBusinessConfig item : data) {
    					for(AgentBusinessConfig agentBusiCfg : agentBusiCfgList) {
    						if(item.getUserId().equals(agentBusiCfg.getUserId()) && 
    								agentBusiCfg.getBusinessType().equals(item.getBusinessType())) {
    							if(agentBusiCfg.getServiceChargeRatio() > busiCfg.getServiceChargeRatio()) {
    								item.setIncomeRatio(agentBusiCfg.getServiceChargeRatio() - busiCfg.getServiceChargeRatio());
    					    	}
    							break;
    						}
    					}
    				}
				}
				return data;
			}
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
    	return null;
    }
    
    public Long countJoinBySearch(AgentReferrerBusinessConfigSearch search) {
    	Conditions condition = dao.buildConditions(search);
    	condition.and().likeBoth("user.name", search.getUserName());
    	condition.and().is("user.phone", search.getUserPhone());
    	
    	try {
			return dao.countJoin(condition);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
    	return 0L;
    }

    public List<AgentReferrerBusinessConfig> findJoinByUserId(Long userId){
    	if(userId != null) {
    		Conditions condition = new Conditions(AgentReferrerBusinessConfig.class);
    		condition.and().is("userId", userId);
    		
    		try {
    			List<AgentReferrerBusinessConfig> data = dao.findJoinByCondition(condition);
    			if(data != null && data.size() > 0) {
    				List<AgentBusinessConfig> agentBusiCfgList = AgentBusinessConfigService.self().findByUserId(userId);
    				if(agentBusiCfgList != null && agentBusiCfgList.size() > 0) {
    					BusinessConfig busiCfg = ConfigUtils.getBusinessConfig();
    					for(AgentReferrerBusinessConfig item : data) {
        					for(AgentBusinessConfig agentBusiCfg : agentBusiCfgList) {
        						if(agentBusiCfg.getBusinessType().equals(item.getBusinessType())) {
        							if(agentBusiCfg.getServiceChargeRatio() > busiCfg.getServiceChargeRatio()) {
        								item.setIncomeRatio(agentBusiCfg.getServiceChargeRatio() - busiCfg.getServiceChargeRatio());
        					    	}
        							break;
        						}
        					}
        				}
    				}
    				return data;
    			}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
    	}
    	return null;
    }
    
    public List<AgentReferrerUser>findReferrerUserBySearch(AgentReferrerBusinessConfigSearch search
    		,Integer pageNo,Integer pageLimit){
    	Conditions condition = dao.buildConditions(search);
    	condition.and().likeBoth("user.name", search.getUserName());
    	condition.and().is("user.phone", search.getUserPhone());

    	try {
    		List<AgentReferrerUser> agentReferrerUserList =  dao.findGroupReferrerUserId(condition, pageNo, pageLimit);
			if(agentReferrerUserList != null && agentReferrerUserList.size() > 0) {
				List<Long> userIds = new ArrayList<>();
				for (AgentReferrerUser agentReferrerUser : agentReferrerUserList) {
	                userIds.add(agentReferrerUser.getReferrerUserId());
	            }
				
				List<User> userList = UserService.self().findByUserIds(userIds);
			    if (userList != null && userList.size() > 0) {
			    	for (AgentReferrerUser agentReferrerUser : agentReferrerUserList) {
			    		for(User user : userList) {
				    		if (user.getId().equals(agentReferrerUser.getReferrerUserId())) {
				    			agentReferrerUser.setReferrerUser(user);
	                            break;
	                        }
			    		}
		             }
				 }
			}
			return agentReferrerUserList;
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
    	return null;
    }
    
    public Long countReferrerUserBySearch(AgentReferrerBusinessConfigSearch search){
    	Conditions condition = dao.buildConditions(search);
    	condition.and().likeBoth("user.name", search.getUserName());
    	condition.and().is("user.phone", search.getUserPhone());

    	try {
			return dao.countGroupReferrerUserId(condition);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
    	return 0L;
    }
    
    public List<AgentReferrerCount> findReferrerCount(Long referrerUserId, Integer pageNo, Integer pageLimit){
    	if(referrerUserId != null) {
	        Conditions conditions = new Conditions(AgentReferrerBusinessConfig.class);
	        conditions.and().is("referrerUserId", referrerUserId);
	        
	        try {
	            return dao.countGroupUserId(conditions,pageNo,pageLimit);
	        } catch (SQLException e) {
	            log.error(e.getMessage(),e);
	        }
    	}
        return null;
    }
    
    public AgentReferrerBusinessConfig getByKeys(Long userId,Long referrerUserId,String businessType) {
    	if(userId != null && referrerUserId != null && businessType != null) {
    		Conditions condition = new Conditions(AgentReferrerBusinessConfig.class);
    		condition.and().is("userId", userId);
    		condition.and().is("referrerUserId", referrerUserId);
    		condition.and().is("businessType", businessType);
    		
    		try {
    			AgentReferrerBusinessConfig entity = dao.get(condition);
				if(entity != null) {
					BusinessConfig busiCfg = ConfigUtils.getBusinessConfig();
			    	AgentBusinessConfig agentBusiCfg = AgentBusinessConfigService.self().getByKeys(entity.getUserId(), entity.getBusinessType());
			    	if(agentBusiCfg != null && agentBusiCfg.getServiceChargeRatio() > busiCfg.getServiceChargeRatio()) {
			    		entity.setIncomeRatio(agentBusiCfg.getServiceChargeRatio() - busiCfg.getServiceChargeRatio());
			    	}
			    	return entity;
				}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
    	}
    	return null;
    }
    
    public AgentReferrerBusinessConfig getJoinByKeys(Long userId,Long referrerUserId,String businessType) {
    	if(userId != null && referrerUserId != null && businessType != null) {
    		Conditions condition = new Conditions(AgentReferrerBusinessConfig.class);
    		condition.and().is("userId", userId);
    		condition.and().is("referrerUserId", referrerUserId);
    		condition.and().is("businessType", businessType);
    		
    		try {
    			AgentReferrerBusinessConfig entity = dao.getJoin(condition);
				if(entity != null) {
					BusinessConfig busiCfg = ConfigUtils.getBusinessConfig();
			    	AgentBusinessConfig agentBusiCfg = AgentBusinessConfigService.self().getByKeys(entity.getUserId(), entity.getBusinessType());
			    	if(agentBusiCfg != null && agentBusiCfg.getServiceChargeRatio() > busiCfg.getServiceChargeRatio()) {
			    		entity.setIncomeRatio(agentBusiCfg.getServiceChargeRatio() - busiCfg.getServiceChargeRatio());
			    	}
			    	return entity;
				}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
    	}
    	return null;
    }
    
    public AgentReferrerBusinessConfig getByKeys(Long userId,String businessType) {
    	if(userId != null && businessType != null) {
    		Conditions condition = new Conditions(AgentReferrerBusinessConfig.class);
    		condition.and().is("userId", userId);
    		condition.and().is("businessType", businessType);
    		
    		try {
				return dao.get(condition);
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
    	}
    	return null;
    }
    
    public AgentReferrerBusinessConfig getJoinByKeys(Long userId,String businessType) {
    	if(userId != null && businessType != null) {
    		Conditions condition = new Conditions(AgentReferrerBusinessConfig.class);
    		condition.and().is("userId", userId);
    		condition.and().is("businessType", businessType);
    		
    		try {
				return dao.getJoin(condition);
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
    	}
    	return null;
    }
    
    public boolean add(AgentReferrerBusinessConfig entity,User user) throws LogicException{
    	if(user.getId() == null) {
    		if(StringTools.isNotBlank(user.getPhone())) {
    			User referrerUser = UserService.self().getByPhone(user.getPhone());
    			if(referrerUser != null) {
    				user.setId(referrerUser.getId());
    			}
    		}else {
    			throw new LogicException("请填写推荐人手机号");
    		}
    	}
    	
    	AgentReferrerBusinessConfig temp = getByKeys(entity.getUserId(),entity.getBusinessType());
    	if(temp != null) {
    		throw new LogicException("已存在该业务推荐人");
    	}
    	
    	if(user.getId() != null) {
	    	entity.setReferrerUserId(user.getId());
	    	entity.setCreateDate(new Date());
	    	try {
				return dao.insert(entity) > 0;
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
    	}else {
    		JdbcSession.begin();
    		try {
    			if(UserService.self().add(user)) {
    				entity.setReferrerUserId(user.getId());
    		    	entity.setCreateDate(new Date());
    				if(dao.insert(entity) > 0) {
    					JdbcSession.commit();
    					return true;
    				}
    			}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}finally {
				JdbcSession.end();
			}
    	}
    	return false;
    }
    
    public boolean deleteByKeys(Long userId,Long referrerUserId,String businessType) throws LogicException{
    	if(userId != null && referrerUserId != null && businessType != null) {
    		Conditions condition = new Conditions(AgentReferrerBusinessConfig.class);
    		condition.and().is("userId", userId);
    		condition.and().is("referrerUserId", referrerUserId);
    		condition.and().is("businessType", businessType);
    		
    		try {
				return dao.deleteByCondition(condition) > 0;
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
    	}
    	return false;
    }
}
